package com.fjec.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjec.common.aliyun.sms.AliyunSmsHelper;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.enums.EnumWXMessageTemplate;
import com.fjec.common.okhttp.OkHttp;
import com.fjec.common.protocol.FjecFruitsProto;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.JsonUtil;
import com.fjec.common.wx.WxAccessTokenHelper;
import com.fjec.common.wx.WxProperties;
import com.fjec.im.entity.BizSystemMessage;
import com.fjec.im.mapper.BizSystemMessageMapper;
import com.fjec.im.service.IBizSystemMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.im.service.ICommonService;
import com.fjec.im.view.SystemMessageVO;
import com.fjec.user.entity.SysUser;
import com.fjec.user.service.ISysUserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 004.系统消息表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-10-20
 */
@Service
public class BizSystemMessageServiceImpl extends ServiceImpl<BizSystemMessageMapper, BizSystemMessage> implements IBizSystemMessageService {

    @Resource
    private BizSystemMessageMapper mapper;

    @Resource
    private ISysUserService sysUserService;

    @Autowired
    private WxAccessTokenHelper wxAccessTokenHelper;

    @Autowired
    private WxProperties wxProperties;

    @Autowired
    private OkHttp okHttp;

    @Autowired
    private ICommonService commonService;

    @Override
    public void handleMessage(Message message) throws Exception {
        FjecFruitsProto.FjecFruitsMsg msg = FjecFruitsProto.FjecFruitsMsg.parseFrom(message.getBody());
        FjecFruitsProto.SysMsg sysMsg = msg.getSysMsg();
        // 小程序内消息表
        BizSystemMessage entity = new BizSystemMessage();
        entity.setId(sysMsg.getMsgId());
        entity.setMsgType(sysMsg.getMsgType());
        entity.setBizType(sysMsg.getBizType());
        entity.setTitle(sysMsg.getTitle());
        entity.setContent(sysMsg.getContent());
        entity.setCreateTime(DateUtil.nowLdt());
        entity.setBizData(sysMsg.getBizDataMap());
        entity.setReaded(0);
        entity.setUserId(sysMsg.getUserId());
        Long delayTime = sysMsg.getDelay();
        if (delayTime != null && delayTime > 0) {
            entity.setDelayTime(DateUtil.milli2Ldt(delayTime));
        } else {
            entity.setDelayTime(DateUtil.nowLdt());
        }
        mapper.insert(entity);

        // 发送微信推送消息
        Integer tId = sysMsg.getBizType();
        if (tId == 9011)
            tId = 9010;
        if (tId == 9001) {
            // 新订单通知，发短信 SMS_205887734
            SysUser user = sysUserService.getById(entity.getUserId());
            String phone = user.getPhone();
            commonService.sendNewOrder(phone);

        } else if (tId == 9002) {
            // 催促发货，发短信 SMS_205887744
            SysUser user = sysUserService.getById(entity.getUserId());
            String phone = user.getPhone();
            commonService.sendRemindDeliver(phone);
        } else {
            Map<String, String> bizDataMap = sysMsg.getBizDataMap();
            String openId = bizDataMap.get("openId");

            String accessToken = wxAccessTokenHelper.getWxCenterAccessToken();
//            String accessToken = "39_t4Y2DhR087DfJUaPELvsDuL9hIqZyv2vTf7rPk8a4b_mqjDbmko7wu2p6gyTmm5Zgh7kShD5Pv3JdKq87-pSt5oKHoa4P1QiA1zHheRFc3vHoamCzUR8pCAOathLUSYX1qKHQ7HNQ5ybq40fNTJjAEAIOE";
            String wxUrl = wxProperties.getSendSubscribeMessageUrl() + "?access_token=" + accessToken;


            EnumWXMessageTemplate template;
            try {
                template = EnumWXMessageTemplate.valueOf("TEMP_" + tId);
            } catch (IllegalArgumentException e) {
                return;
            }

            String templateId = template.getTemplateId();
            String path = template.getPath();

            Map<String, Object> body = new HashMap<>();
            body.put("touser", openId);
            body.put("template_id", templateId);
            body.put("page", path);
            Map<String, Map<String, Object>> contentJson = this.buildSubscribeMessageData(tId, bizDataMap);
            body.put("data", contentJson);
            body.put("miniprogram_state", wxProperties.getMiniprogramState());

            String response = okHttp.postJson(wxUrl, JsonUtil.toJson(body));
            Map<String, Object> result = JsonUtil.jsonToMap(response);
            Integer errCode = MapUtils.getInteger(result, "errcode");
            if (errCode != 0 && errCode != 43101) {
                // do nothing
            }
        }
    }

    private Map<String, Map<String, Object>> buildSubscribeMessageData(Integer tId, Map<String, String> bizDataMap) {
        Map<String, Map<String, Object>> result = new HashMap<>();
        switch (tId) {
            // todo: tId与template对应关系

            case 9001: // 新订单通知
                String amount = MapUtils.getString(bizDataMap, "amount"); // 订单总额
                String spuName = MapUtils.getString(bizDataMap, "spuName"); // 商品名称
                String date = MapUtils.getString(bizDataMap, "date"); // 下单时间
                String orderId = MapUtils.getString(bizDataMap, "orderId"); // 订单号
                String remark = MapUtils.getString(bizDataMap, "remark"); // 买家备注

                Map<String, Object> m11 = new HashMap<>();
                m11.put("value", amount);
                result.put("amount1", m11);

                Map<String, Object> m12 = new HashMap<>();
                m12.put("value", spuName);
                result.put("thing11", m12);

                Map<String, Object> m13 = new HashMap<>();
                m13.put("value", date);
                result.put("date5", m13);

                Map<String, Object> m14 = new HashMap<>();
                m14.put("value", orderId);
                result.put("character_string7", m14);

                Map<String, Object> m15 = new HashMap<>();
                m15.put("value", remark);
                result.put("thing16", m15);
                break;

            case 9002: // 催促发货提醒
                String character_string1 = MapUtils.getString(bizDataMap, "orderId"); // 订单Id
                String thing2 = MapUtils.getString(bizDataMap, "spuName"); // 商品名称
                String thing5 = MapUtils.getString(bizDataMap, "remark"); // 备注

                Map<String, Object> m21 = new HashMap<>();
                m21.put("value", character_string1);
                result.put("character_string1", m21);

                Map<String, Object> m22 = new HashMap<>();
                m22.put("value", thing2);
                result.put("thing2", m22);

                Map<String, Object> m23 = new HashMap<>();
                m23.put("value", thing5);
                result.put("thing5", m23);
                break;

            case 9009: // 订单发货提醒
                String thing22 = MapUtils.getString(bizDataMap, "shopName"); // 商品名称
                String thing23 = MapUtils.getString(bizDataMap, "spuList"); // 商品清单
                String thing14 = MapUtils.getString(bizDataMap, "deliComp"); // 快递公司
                String character_string13 = MapUtils.getString(bizDataMap, "deliNum"); // 快递单号
                String thing12 = MapUtils.getString(bizDataMap, "notification"); // 温馨提示

                Map<String, Object> m31 = new HashMap<>();
                m31.put("value", thing22);
                result.put("thing22", m31);

                Map<String, Object> m32 = new HashMap<>();
                m32.put("value", thing23);
                result.put("thing23", m32);

                Map<String, Object> m33 = new HashMap<>();
                m33.put("value", thing14);
                result.put("thing14", m33);

                Map<String, Object> m34 = new HashMap<>();
                m34.put("value", character_string13);
                result.put("character_string13", m34);

                Map<String, Object> m35 = new HashMap<>();
                m35.put("value", thing12);
                result.put("thing12", m35);
                break;

            case 9003: // 确认收货通知
                String character_string1a = MapUtils.getString(bizDataMap, "orderId"); // 订单编号
                String thing6 = MapUtils.getString(bizDataMap, "buyer"); // 下单人
                String thing2a = MapUtils.getString(bizDataMap, "spuName"); // 商品名称

                Map<String, Object> m41 = new HashMap<>();
                m41.put("value", character_string1a);
                result.put("character_string1", m41);

                Map<String, Object> m42 = new HashMap<>();
                m42.put("value", thing6);
                result.put("thing6", m42);

                Map<String, Object> m43 = new HashMap<>();
                m43.put("value", thing2a);
                result.put("thing2", m43);
                break;

            case 9006: // 订单结算通知
                String amount2 = MapUtils.getString(bizDataMap, "distributionAmount"); // 结算金额
                String phrase3 = MapUtils.getString(bizDataMap, "distributionStatus"); // 结算状态
                String thing4 = MapUtils.getString(bizDataMap, "notification"); // 温馨提示

                Map<String, Object> m51 = new HashMap<>();
                m51.put("value", amount2);
                result.put("amount2", m51);

                Map<String, Object> m52 = new HashMap<>();
                m52.put("value", phrase3);
                result.put("phrase3", m52);

                Map<String, Object> m53 = new HashMap<>();
                m53.put("value", thing4);
                result.put("thing4", m53);
                break;

            case 9010: // 审核结果通知
                String phrase1 = MapUtils.getString(bizDataMap, "reviewResult"); // 结算状态
                String thing4a = MapUtils.getString(bizDataMap, "notification"); // 温馨提示

                Map<String, Object> m61 = new HashMap<>();
                m61.put("value", phrase1);
                result.put("phrase1", m61);

                Map<String, Object> m62 = new HashMap<>();
                m62.put("value", thing4a);
                result.put("thing4", m62);
                break;

            case 7: // 申请结果通知
                String thing1 = MapUtils.getString(bizDataMap, "applicationDesc"); // 申请描述
                String phrase2 = MapUtils.getString(bizDataMap, "applicationResult"); // 申请结果
                String thing5a = MapUtils.getString(bizDataMap, "remark"); // 备注

                Map<String, Object> m71 = new HashMap<>();
                m71.put("value", thing1);
                result.put("thing1", m71);

                Map<String, Object> m72 = new HashMap<>();
                m72.put("value", phrase2);
                result.put("phrase2", m72);

                Map<String, Object> m73 = new HashMap<>();
                m73.put("value", thing5a);
                result.put("thing5", m73);
                break;

            default:
        }
        return result;
    }

    @Override
    public JsonResult getSystemMessageList(Page page) throws Exception {
        Long userId = AccountInfo.getUserId();
        QueryWrapper<BizSystemMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UserId", userId)
                .orderByAsc("Readed")
                .orderByDesc("CreateTime");
        Page<BizSystemMessage> resultPage = mapper.selectPage(page, queryWrapper);
        List<SystemMessageVO> resultList = new ArrayList<>();
        for (BizSystemMessage entity : resultPage.getRecords()) {
            SystemMessageVO view = new SystemMessageVO();
            BeanUtils.copyProperties(view, entity);
            view.setDisplayTime(DateUtil.ldt2Milli(entity.getCreateTime()) / 1000);
            resultList.add(view);
        }
        return JsonResult.success()
                .total(resultPage.getTotal())
                .data(resultList)
                .build();
    }

    @Override
    public JsonResult readSystemMessage(Long msgId) throws Exception {
        BizSystemMessage entity = new BizSystemMessage();
        entity.setId(msgId);
        entity.setReaded(1);
        entity.setUpdateTime(DateUtil.nowLdt());
        mapper.updateById(entity);
        return JsonResult.success().build();
    }
}
